/**
 * @author Linrui
 * @since 2011-03-27
 * 企业的业务层封装类
 */
package com.qeado.company.service.implement;

import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qeado.company.dao.CompanyDao;
import com.qeado.company.model.Company;
import com.qeado.company.service.CompanyService;
import com.qeado.product.model.Product;
import com.qeado.user.dao.UserDao;
import com.qeado.user.model.User;
import com.qeado.util.FileUpload;
import com.qeado.util.PageHelper;

@Service
public class CompanyServiceImplement implements CompanyService {

	@Autowired
	private CompanyDao companyDao;

	@Autowired
	private UserDao userDao;

	public boolean deleteCompany(String id) {
		return companyDao.deleteCompany(id);
	}

	public String insertCompany(Company company, User user) {
		company.setId(UUID.randomUUID().toString());
		company.setActiveFlag("1");
		company.setPageViews(0);
		company.setCreator(user.getUserName());
		if (companyDao.insertCompany(company) == true) {
			user.setCompanyID(company.getId());
			user.setAdminFlag("1"); // 创建公司的用户，将被设置为管理员
			userDao.updateUser(user);
			return "success";
		} else
			return "fail";
	}

	public String insertCompany(Company company, FileUpload upload, User user) {
		if (upload == null) {
			company.setFileName("default/default.gif");
			return insertCompany(company, user);
		} else {
			upload.upload();
			company.setFileName(upload.getImageFileName());
			return insertCompany(company, user);
		}
	}

	public PageHelper listAll(int pageNum, int pageSize, String orderBy,
			String asc) {
		return companyDao.listAll(pageNum, pageSize, orderBy, asc);
	}

	public PageHelper listByKey(int pageNum, int pageSize, String orderBy,
			String asc, String key) {
		StringBuffer temp = new StringBuffer();
		temp.append("%");
		temp.append(key);
		temp.append("%");
		return companyDao.listByKey(pageNum, pageSize, orderBy, asc,
				temp.toString());
	}

	public Company queryById(String id) {
		return companyDao.queryById(id);
	}

	public boolean updateCompany(Company company) {
		return companyDao.updateCompany(company)  ;
	}

	public boolean updateCompany(Company company, FileUpload upload) {
		if (upload == null) {
			return updateCompany(company);
		} else {
			upload.upload();
			company.setFileName(upload.getImageFileName());
			return updateCompany(company);
		}
	}

}
